package com.heaven.map.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heaven.map.pojo.vo.ResponseInfo;
import com.heaven.map.pojo.po.TAdmin;
import com.heaven.map.mapper.TAdminMapper;
import com.heaven.map.service.ITAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heaven.map.utils.CodeEnum;
import com.heaven.map.utils.JWTUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Heaven
 * @since 2021-10-03
 */
@Service
public class TAdminServiceImpl extends ServiceImpl<TAdminMapper, TAdmin> implements ITAdminService {

    @Autowired
    private TAdminMapper tAdminMapper;

    @Autowired
    private JWTUtils jwtUtils;
    @Value("${self.shiro.secret}")
    private String secret;
    @Override
    public ResponseInfo verify(TAdmin admin) {
        String email = admin.getEmail();
        Md5Hash password = new Md5Hash(admin.getPassword(),secret,1024);
        TAdmin S_data = tAdminMapper.selectOne(new QueryWrapper<TAdmin>().eq("email", email));
        if (S_data == null){
            return new ResponseInfo(null,"该账号不存在",CodeEnum.Unauthorized.getCode());
        }
        else {
            if ( password.toHex().equals(S_data.getPassword())){
                String token = jwtUtils.getToken(email);
                return new ResponseInfo(token,"登录成功",CodeEnum.OK.getCode());
            }
            else{
                return new ResponseInfo(null,"密码错误",CodeEnum.Unauthorized.getCode());
            }
        }
    }

    @Override
    public ResponseInfo modify(String password, String token) {
        TAdmin tAdmin = new TAdmin();
        DecodedJWT decodedJWT = jwtUtils.verify(token);
        String email = decodedJWT.getClaim("email").asString();
        tAdmin.setEmail(email);
        Md5Hash passwd = new Md5Hash(password, secret, 1024);
        tAdmin.setPassword(passwd.toHex());
        tAdminMapper.update(tAdmin, new QueryWrapper<TAdmin>().eq("email", tAdmin.getEmail()));
        //返回参数1：新的Token值，参数2提示信息，参数3：状态码
        return new ResponseInfo(jwtUtils.getToken(email),"修改成功", CodeEnum.OK.getCode());
    }

    @Override
    public ResponseInfo verifyToken(String token) {
        return null;
    }
}
